/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on Sep 24, 2011, 4:20:38 PM
 */
package GUI;

import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import phoneHughes.Credentials;
import sql.Connector;
import utilities.DateConverter;
import utilities.IDCreator;
import utilities.MessageDialog;
import utilities.StringValidation;
import utilities.TableParser;

/**
 *
 * @author Alex Hughes
 */
public class ContactFrame extends GUI {

    private GUI previousFrame;
    private Connector connector;
    //
    private int contactID;
    private boolean newContact;
    private boolean fieldCheckSuccesfull = false;

    /** Creates new form MainFrame */
    //Constructor for the NEW Contact
    public ContactFrame(GUI aPreviousFrame, Connector aConnector) {
        previousFrame = aPreviousFrame;
        connector = aConnector;
        newContact = true;

        initComponents();
        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                disposeAndShowPrevious();
            }
        });

        try {
            contactID = IDCreator.createID(connector, "Contact");
        } catch (SQLException ex) {
            MessageDialog.conError(this);
            previousFrame.setVisible(true);
            this.dispose();
            Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
        super.setFrameLocationCenter(this);
        this.setVisible(true);
    }

    public ContactFrame(GUI aPreviousFrame, Connector aConnector, int aContactID) {
        previousFrame = aPreviousFrame;
        connector = aConnector;
        contactID = aContactID;
        newContact = false;

        initComponents();
        this.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                disposeAndShowPrevious();
            }
        });


        try {
            loadContact();
            loadTelephones();
            loadEmails();
        } catch (SQLException ex) {
            MessageDialog.conError(this);
            Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        super.setFrameLocationCenter(this);
        this.setVisible(true);
    }

    private void disposeAndShowPrevious() {
        this.dispose();
        previousFrame.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        nameField = new javax.swing.JTextField();
        surnameField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        commentArea = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        phoneTable = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        emailTable = new javax.swing.JTable();
        addPhoneBtn = new javax.swing.JButton();
        changePhoneBtn = new javax.swing.JButton();
        removePhoneBtn = new javax.swing.JButton();
        addEmailBtn = new javax.swing.JButton();
        changeEmailBtn = new javax.swing.JButton();
        removeEmailBtn = new javax.swing.JButton();
        saveBtn = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("New Contact");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("name:");

        jLabel2.setText("surname:");

        nameField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                nameFieldMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                nameFieldMousePressed(evt);
            }
        });

        surnameField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                surnameFieldMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                surnameFieldMousePressed(evt);
            }
        });

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("comments"));

        commentArea.setColumns(20);
        commentArea.setLineWrap(true);
        commentArea.setRows(5);
        commentArea.setWrapStyleWord(true);
        commentArea.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                commentAreaMouseReleased(evt);
            }
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                commentAreaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(commentArea);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                            .addComponent(surnameField, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(surnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("Phones"));

        phoneTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(phoneTable);

        jScrollPane3.setBorder(javax.swing.BorderFactory.createTitledBorder("Emails"));

        emailTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(emailTable);

        addPhoneBtn.setText("Add");
        addPhoneBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addPhoneBtnActionPerformed(evt);
            }
        });

        changePhoneBtn.setText("Change");
        changePhoneBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changePhoneBtnActionPerformed(evt);
            }
        });

        removePhoneBtn.setText("Remove");
        removePhoneBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removePhoneBtnActionPerformed(evt);
            }
        });

        addEmailBtn.setText("Add");
        addEmailBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addEmailBtnActionPerformed(evt);
            }
        });

        changeEmailBtn.setText("Change");
        changeEmailBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeEmailBtnActionPerformed(evt);
            }
        });

        removeEmailBtn.setText("Remove");
        removeEmailBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeEmailBtnActionPerformed(evt);
            }
        });

        saveBtn.setText("Save Changes");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        jButton1.setText("<Back");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addPhoneBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(changePhoneBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(removePhoneBtn))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addEmailBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(changeEmailBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(removeEmailBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(saveBtn)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addPhoneBtn)
                    .addComponent(changePhoneBtn)
                    .addComponent(removePhoneBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(removeEmailBtn)
                    .addComponent(changeEmailBtn)
                    .addComponent(addEmailBtn)
                    .addComponent(saveBtn)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
        commit(false);
    }//GEN-LAST:event_saveBtnActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        cancelButton();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void addPhoneBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addPhoneBtnActionPerformed
        addPhoneButton();
    }//GEN-LAST:event_addPhoneBtnActionPerformed

    private void addEmailBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addEmailBtnActionPerformed
        addEmailButton();
    }//GEN-LAST:event_addEmailBtnActionPerformed

    private void changePhoneBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changePhoneBtnActionPerformed
        changePhoneButton();
    }//GEN-LAST:event_changePhoneBtnActionPerformed

    private void changeEmailBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeEmailBtnActionPerformed
        changeEmailButton();
    }//GEN-LAST:event_changeEmailBtnActionPerformed

    private void removePhoneBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removePhoneBtnActionPerformed
        removePhoneButton();
    }//GEN-LAST:event_removePhoneBtnActionPerformed

    private void removeEmailBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeEmailBtnActionPerformed
        removeEmailButton();
    }//GEN-LAST:event_removeEmailBtnActionPerformed

    private void nameFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_nameFieldMouseClicked
        popupMenuField(nameField);
    }//GEN-LAST:event_nameFieldMouseClicked

    private void nameFieldMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_nameFieldMousePressed
        popupMenuField(nameField);
    }//GEN-LAST:event_nameFieldMousePressed

    private void surnameFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_surnameFieldMouseClicked
        popupMenuField(surnameField);
    }//GEN-LAST:event_surnameFieldMouseClicked

    private void surnameFieldMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_surnameFieldMousePressed
        popupMenuField(surnameField);
    }//GEN-LAST:event_surnameFieldMousePressed

    private void commentAreaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_commentAreaMouseClicked
        popupMenuArea(commentArea);
    }//GEN-LAST:event_commentAreaMouseClicked

    private void commentAreaMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_commentAreaMouseReleased
        popupMenuArea(commentArea);
    }//GEN-LAST:event_commentAreaMouseReleased
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addEmailBtn;
    private javax.swing.JButton addPhoneBtn;
    private javax.swing.JButton changeEmailBtn;
    private javax.swing.JButton changePhoneBtn;
    private javax.swing.JTextArea commentArea;
    private javax.swing.JTable emailTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField nameField;
    private javax.swing.JTable phoneTable;
    private javax.swing.JButton removeEmailBtn;
    private javax.swing.JButton removePhoneBtn;
    private javax.swing.JButton saveBtn;
    private javax.swing.JTextField surnameField;
    // End of variables declaration//GEN-END:variables

    private void cancelButton() {
        disposeAndShowPrevious();
    }

    private void addPhoneButton() {
        if (newContact) {
            commit(true);
        }
        if (!AddDetailFrame.isInstanceAlive()) {
            AddDetailFrame d = new AddDetailFrame(this, connector, "Telephone", contactID);
        }
    }

    private void addEmailButton() {
        if (newContact) {
            commit(true);
        }
        if (!AddDetailFrame.isInstanceAlive()) {
            AddDetailFrame d = new AddDetailFrame(this, connector, "Email", contactID);
        }
    }

    private void changePhoneButton() {
        int detailID = TableParser.checkRowsAndGetID(phoneTable, this);

        if (!AddDetailFrame.isInstanceAlive() && detailID != -1) {    //negative logic
            AddDetailFrame d = new AddDetailFrame(this, connector, "Telephone", contactID, detailID);
        }
    }

    private void changeEmailButton() {
        int detailID = TableParser.checkRowsAndGetID(emailTable, this);

        if (!AddDetailFrame.isInstanceAlive() && detailID != -1) {    //negative logic
            AddDetailFrame d = new AddDetailFrame(this, connector, "Email", contactID, detailID);
        }
    }

    private void removePhoneButton() {
        int phoneID = TableParser.checkRowsAndGetID(phoneTable, this);

        if (phoneID != -1) {
            int answer = MessageDialog.deleteQuestion(this);
            if (answer == JOptionPane.YES_OPTION) {
                try {
                    connector.sendUpdate(""
                            + "DELETE FROM Telephone WHERE TelephoneID = " + phoneID);
                    reloadInfoTable();
                } catch (SQLException ex) {
                    MessageDialog.conError(this);
                    Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void removeEmailButton() {
        int emailID = TableParser.checkRowsAndGetID(emailTable, this);

        if (emailID != -1) {
            int answer = MessageDialog.deleteQuestion(this);
            if (answer == JOptionPane.YES_OPTION) {
                try {
                    connector.sendUpdate(""
                            + "DELETE FROM Email WHERE EmailID = " + emailID);
                    reloadInfoTable();
                } catch (SQLException ex) {
                    MessageDialog.conError(this);
                    Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void loadContact() throws SQLException {
        ResultSet contactR = connector.sendQuery(""
                + "SELECT * "
                + "FROM Contact "
                + "WHERE ContactID = " + contactID);

        while (contactR.next()) {
            String name = StringValidation.unCamouflageString(contactR.getString("Name"));
            String surname = StringValidation.unCamouflageString(contactR.getString("Surname"));

            nameField.setText(name);
            surnameField.setText(surname);
            commentArea.setText(StringValidation.unCamouflageString(contactR.getString("Comments")));
            this.setTitle(contactID + " - " + name + " " + surname + " "
                    + DateConverter.SqlStringToString(contactR.getDate("_dateModified").toString())
                    + " || " + contactR.getTime("_dateModified"));
        }
    }
    
    @Override
    public void reloadInfoTable() throws SQLException{
            loadTelephones();
            loadEmails();
    }

    private void loadEmails() throws SQLException {
        String query = ""
                + "SELECT e.* "
                + "FROM Email e "
                + "INNER JOIN ContactEmail ce ON e.EmailID = ce.EmailID "
                + "WHERE ce.ContactID = " + contactID;

        TableParser.fillTable(query, emailTable, connector);
    }

    private void loadTelephones() throws SQLException {
        String query = ""
                + "SELECT t.* "
                + "FROM Telephone t "
                + "INNER JOIN ContactTelephone ct ON t.TelephoneID = ct.TelephoneID "
                + "WHERE ct.ContactID = " + contactID;

        TableParser.fillTable(query, phoneTable, connector);
    }

    private void checkFieldData() {
        boolean name = StringValidation.validStringLength(nameField.getText(), 100);
        boolean surname = StringValidation.validStringLength(surnameField.getText(), 100);

        fieldCheckSuccesfull = (name && surname);
    }

    private void insertNewContact() throws SQLException {
        connector.sendUpdate(""
                + "INSERT INTO `Contact` (`ContactID`) VALUES (" + contactID + ") ");
        newContact = false;
    }

    private void commit(boolean isMandatory) {  //mandatory commit do not show success confirmation dialogue.
        checkFieldData();
        if (fieldCheckSuccesfull) {
            if (newContact) {
                try {
                    insertNewContact();
                } catch (SQLException ex) {
                    MessageDialog.conError(this);
                    disposeAndShowPrevious();
                    Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            try {
                connector.sendUpdate(""
                        + "UPDATE Contact "
                        + "SET Name = '" + StringValidation.camouflageString(nameField.getText())
                        + "', Surname = '" + StringValidation.camouflageString(surnameField.getText())
                        + "', Comments = '" + StringValidation.camouflageString(commentArea.getText()) + "' "
                        + "WHERE ContactID = " + contactID);
                if (!isMandatory) {
                    MessageDialog.saveSuccess(this);
                }
            } catch (SQLException ex) {
                MessageDialog.conError(this);
                disposeAndShowPrevious();
                Logger.getLogger(ContactFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            MessageDialog.stringError(this);
        }
    }
}
